#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<queue>
#include<unordered_map>
#include<string>
using namespace std;
const int N = 4;
char g[N][N];
string start;
unordered_map<string, int> d;
int dx[] = { 1,0,-1,0 }, dy[] = { 0,-1,0,1 };
int bfs()
{
    string end = "12345678x";
    queue<string> q;
    q.push(start);
    d[start] = 0;
    while(q.size())
    {
        auto s = q.front();
        q.pop();
        int dist = d[s];
        if (s == end) return dist;
        int k = s.find('x');
        int a = k / 3, b = k % 3;
        for (int i = 0; i < 4; i++)
        {
            int x = a + dx[i], y = b + dy[i];
            if (x < 0 || x>2 || y < 0 || y>2) continue;
            swap(s[x * 3 + y], s[k]);
            if (!d.count(s))
            {
                d[s] = dist + 1;
                q.push(s);
            }
            swap(s[x * 3 + y], s[k]);
        }
    }
    return -1;
}
int main()
{
    for (int i = 0; i < 3; i++)
    {
        for (int j = 0; j < 3; j++)
        {
            cin >> g[i][j];
            start += g[i][j];
        }
    }
    cout << bfs() << endl;
    return 0;
}